package com.newlink.building.common_base.manager

import android.content.Context
import com.newlink.building.common_base.model.bean.CountryCodeBean
import com.newlink.building.common_base.utils.NLog
import org.json.JSONArray

/**
 * @Author: Jake
 * @Date: 2024-04-08
 * @Description:
 */
object Base_CountryCodeManager {

    val mAllCountryList: MutableList<CountryCodeBean> = mutableListOf()
    var mDefaultCountryCodeBean: CountryCodeBean? = null

    fun getDefaultCountryCode(context: Context): CountryCodeBean {
        val languageCode = getLocalLanguageCode(context)
        return if (languageCode == "zh") {
            // 固定使用neutral渠道的配置
            CountryCodeBean("US/CA", "United States/Canada", "1")
        } else {
            CountryCodeBean("US/CA", "United States/Canada", "1")
        }
    }

    private fun getLocalCountryCode(context: Context): String {
        return context.resources.configuration.locale.country
    }

    private fun getLocalLanguageCode(context: Context): String {
        return context.resources.configuration.locale.language
    }

    suspend fun getCountryCodeBeanList(context: Context): List<CountryCodeBean> {

        val countryCodeJson = StringBuffer()

        context.assets.open("country.json").bufferedReader().use { reader ->
            reader.forEachLine {
                countryCodeJson.append(it)
            }
        }
        val ja = JSONArray(countryCodeJson.toString())
        NLog.e("[Jake] :: CountryCodeManager :: $ja")

        for (i in 0 until ja.length()) {
            ja.getJSONObject(i).let {
                val countryCodeBean = CountryCodeBean(
                    it.getString("locale"),
                    it.getString("area"),
                    it.getString("code")
                )
                mAllCountryList.add(countryCodeBean)
            }
        }

        return mAllCountryList
    }
}